<template>
  <div class="weCom">
    <div v-if="customer.weCustomerId" style="height: 100%">
      <div class="sessing-box">
        <div class="login-box" v-if="!isLogin">
          <wxLogin @setIsLogin="setIsLogin" @success="createdComponentDisplay" />
        </div>
        <div class="user-list" style="flex: 1" v-if="wecomFollowUserList.length">
          <div class="chat-view" ref="containerRef">
            <div
              class="chat-item"
              v-for="(item, key) in wecomFollowUserList"
              :key="key"
              :class="key === changeUser ? 'active' : ''"
              @click="selectItem(item, key)"
            >
              <div style="display: flex; align-items: center">
                <div class="chat-img">
                  <canvas
                    :ref="(el) => getDivDom(el, item)"
                    :style="{ background: ColorMap[key % 4] }"
                  ></canvas>
                </div>
                <div class="chat-name">
                  <div class="content-txt">
                    {{ item.userNickname }}
                  </div>
                </div>
              </div>
              <div class="chat-time">
                <div>{{ formatDate(item.createTime * 1000) }}</div>
              </div>
            </div>
          </div>
        </div>
        <div v-else class="color-#6b778c text-14px text-center w-100%">没有更多数据了</div>
        <div id="wechatbox" ref="wechatbox"></div>
      </div>
    </div>
    <div class="noWecom" v-else>
      <div class="weWcomBtn" @click="associaWecom">
        <Icon class="mr-5px" icon="icon-park-outline:peoples" />
        <span>关联企业微信</span>
      </div>
    </div>
  </div>
</template>
<script setup>
import { formatDate } from '@/utils/formatTime'
import wxLogin from '@/views/wecom/user/components/wxLogin.vue'
import * as WeComApiConfigApi from '@/api/wecom/apiconfig'
import * as ww from '@wecom/jssdk'
import weComConfig from '@/utils/weComConfig'

const formData = ref(null)
const jsapiSignature = ref(null)
const changeUser = ref('')
const changeItem = ref('')
const externalUserId = ref('')
const msgList = ref([])
const isLogin = ref(true)
const divDomList = ref(new Map())
const ColorMap = ref([
  'rgb(132, 202, 176)',
  'rgb(188, 158, 221)',
  'rgb(125, 179, 217)',
  'rgb(140, 163, 205)'
])
const limit = ref({
  pageNo: 1,
  pageSize: 10
})
const noMore = ref(false)

const props = defineProps({
  customer: Object,
  wecomFollowUserList: Array,
  userItem: Object,
  isPool: Boolean
})
watch(
  () => divDomList.value,
  (value) => {
    props.wecomFollowUserList.forEach((item) => {
      const canvas = value.get(item.id)
      if (canvas) {
        let companyName = item.userNickname ? item.userNickname.slice(0, 2).toUpperCase() : ''
        let positLeft = 50
        const ctx = canvas.getContext('2d')
        ctx.scale(1, 0.5)
        ctx.font = '100px sans-serif'
        ctx.fillStyle = '#fff'
        ctx.fillText(companyName, positLeft, 180)
      }
    })
  },
  { immediate: true, deep: true }
)
// 初始化
onBeforeMount(() => {
  getWeComApiConfig()
})
const getWeComApiConfig = async () => {
  try {
    formData.value = await WeComApiConfigApi.getWeComApiConfig()
    jsapiSignature.value = await WeComApiConfigApi.getJsapiSignature({
      url: window.location.href
    })
    initComponentSession()
  } finally {
  }
}
const getAgentConfigSignature = async () => {
  return ww.getSignature(jsapiSignature.value.jsapiTicket)
}
const initComponentSession = async () => {
  try {
    ww.register({
      corpId: formData.value.corpId,
      agentId: formData.value.agentId,
      jsApiList: ['selectExternalContact', 'shareAppMessage', 'wwapp.invokeJsApiByCallInfo'],
      getAgentConfigSignature
    })
  } catch {}
  // 会话组件需要确保 WWOpenData 初始化成功
  await ww.initOpenData()
}
const emit = defineEmits(['showWeCom'])
// 显示关联企微
const associaWecom = () => {
  if (props.isPool) return
  emit('showWeCom')
}

const getDivDom = (el, item) => {
  if (el) {
    divDomList.value.set(item.id, el)
  }
}
const toDate = (number) => {
  var date = new Date(number)
  var Y = date.getFullYear() + '-'
  var M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-'
  var D = date.getDate() < 10 ? '0' + date.getDate() : date.getDate()
  var H = date.getHours() < 10 ? '0' + date.getHours() : date.getHours()
  var Min = date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes()
  var S = date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds()

  return Y + M + D + ' ' + H + ':' + Min + ':' + S
}
// 是否登录
const setIsLogin = (val) => {
  isLogin.value = val
}
// 点击详情
const selectItem = (item, key) => {
  changeUser.value = key
  externalUserId.value = item.qwUserId
  changeItem.value = item
  limit.value.pageNo = 1
  msgList.value = []
  noMore.value = false
  getMsgRecordPage()
}
const instance = ref(null)
const getMsgRecordPage = async () => {
  if (noMore.value) return
  const { list } = await WeComApiConfigApi.listByCustomer({
    weUserId: externalUserId.value,
    weCustomerId: props.userItem.externalUserId,
    pageNo: limit.value.pageNo,
    pageSize: limit.value.pageSize
  })
  if (list.length == 0) {
    noMore.value = true
  }
  list.forEach((element) => {
    let sendName = [props.userItem].find((item) => item.externalUserId == element.weUserId)
    let sendName2 = props.wecomFollowUserList.find((item) => item.qwUserId == element.weUserId)
    element.sendTime = toDate(element.sendTime)
    element.weComName = sendName ? sendName.name : sendName2.userNickname
  })
  list.map((item) => {
    msgList.value.unshift(item)
  })
  if (instance.value) {
    instance.value.setData({
      list: msgList.value
    })
  } else {
    createdComponentDisplay()
  }
}
const wechatbox = ref(null)
const createdComponentDisplay = () => {
  if (sessionStorage.getItem('weComCode')) {
    // 校验是否过期
  } else {
    setIsLogin(false)
    return
  }

  if (wechatbox.value) {
    wechatbox.value.innerHTML = '' // 清空容器
  }
  const factory = ww.createOpenDataFrameFactory()
  instance.value = factory.createOpenDataFrame({
    el: wechatbox.value, // “容器”元素，用于挂载展示组件
    template: `
    <scroll-view scroll-y="{{true}}" scroll-top="{{data.scrollTop}}" bindscrolltoupper="scrolltoupper" upper-threshold="{{data.threshold}}" class="scrollCompany">
      <view
        wx:for="{{data.list}}"
        wx:key="msgid"
        class="msg {{item.senderType==1||item.senderType==3?'flexEnd':'flexStart'}}"
        data-index="{{index}}"
      >
        <view class="txtFont">[{{item.weComName}}] {{item.sendTime}}</view>
        <ww-open-message
          class="custom-open-message {{item.senderType==1||item.senderType==3?'activeRight':'activeLeft'}}"
          message-id="{{item.msgid}}"
          secret-key="{{item.secureKey}}"
          open-type="viewMessage"
        />
      </view>
    </scroll-view>
  `,
    style: `
    .scrollCompany{
      height:100%;
    }
    .msg {
      padding:10px;
      padding-top: 20px;
      display:flex;
      flex-direction:column;
    }
    .flexEnd{
      align-items:flex-end;
    }
    .flexStart{
      align-items:flex-start;
    }
    .txtFont{
      font-size:12px;
      margin-bottom:6px;
      color:#494a4d;
    }
    .custom-open-message{
      padding-top: 20px;
      padding: 10px;
      border-radius: 4px;
    }
    .activeRight{
       background: #b3d4ff;
       display: inline-block;
    }
    .activeLeft{
      background: #ebecf0;
      display: inline-block;
    }
  `,
    error: (err) => {
      if (err.errMsg == 'Missing open sid') {
        setIsLogin(false)
      }
    },
    data: {
      list: msgList.value,
      threshold: 20,
      scrollTop: 200
    },
    methods: {
      scrolltoupper() {
        limit.value.pageNo += 1
        getMsgRecordPage()
      }
    }
  })
}
</script>
<style lang="scss" scoped>
.weCom {
  height: 100%;
  background-color: #fff;
  border-radius: 12px;
  box-shadow: 0 2px 8px #172b4d1a;
  margin: 0 8px;
  padding: 16px;
  .noWecom {
    width: 100%;
    height: 100%;
    display: flex;
    justify-content: center;
    align-items: center;
    .weWcomBtn {
      cursor: pointer;
      width: 120px;
      height: 40px;
      text-align: center;
      line-height: 40px;
      border-radius: 4px;
      border: 1px solid #e4e7ed;
      font-size: 14px;
    }
    .weWcomBtn:hover {
      box-shadow: rgba(0, 0, 0, 0.08) 0px 0px 6px 2px;
    }
  }
}
.sessing-box {
  display: flex;
  position: relative;
  height: 100%;
}
.login-box {
  width: 66.6%;
  position: absolute;
  top: 0;
  right: 0;
  z-index: 2;
  height: 100%;
}
canvas {
  width: 30px;
  height: 30px;
  border-radius: 4px;
}

::v-deep #wechatbox {
  flex: 2;
  height: 100%;
  iframe {
    width: 100%;
    height: 100%;
    background: #f4f5f7;

    &::-webkit-scrollbar {
      width: 2px;
    }
    &::-webkit-scrollbar-track {
      background: #f1f1f1;
    }
    &::-webkit-scrollbar-thumb {
      background: #d8d8d8;
    }
    &::-webkit-scrollbar-thumb:hover {
      background: #d8d8d8;
    }
    &::-webkit-scrollbar-thumb:horizontal:start {
      border-top-left-radius: 4px;
      border-bottom-left-radius: 4px;
    }
    &::-webkit-scrollbar-thumb:horizontal:end {
      border-top-right-radius: 4px;
      border-bottom-right-radius: 4px;
    }
  }
}
.user-list {
  height: 100%;
  border-right: 1px solid #e0e1e2;
  .chat-view {
    height: 100%;
    overflow-y: auto;
    display: flex;
    flex-direction: column;
    align-items: center;
    &::-webkit-scrollbar {
      width: 2px;
    }
    &::-webkit-scrollbar-track {
      background: #f1f1f1;
    }
    &::-webkit-scrollbar-thumb {
      background: #d8d8d8;
    }
    &::-webkit-scrollbar-thumb:hover {
      background: #d8d8d8;
    }
    &::-webkit-scrollbar-thumb:horizontal:start {
      border-top-left-radius: 4px;
      border-bottom-left-radius: 4px;
    }
    &::-webkit-scrollbar-thumb:horizontal:end {
      border-top-right-radius: 4px;
      border-bottom-right-radius: 4px;
    }
    .active {
      background: #d1def0;
    }
    .chat-item {
      width: calc(100% - 20px);
      padding: 4px 10px;
      border-bottom: 1px solid #e0e1e2;
      display: flex;
      align-items: center;
      justify-content: space-between;
      cursor: pointer;
      .chat-img {
        position: relative;
        .el-image {
          width: 40px;
          height: 40px;
          border-radius: 50%;
        }
      }
      .chat-name {
        margin-left: 12px;
        width: 150px;
        display: flex;
        flex-direction: column;
        justify-content: space-around;
        .content-title {
          display: flex;
          .pc-name {
            font-size: 16px;
            color: #000;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
            margin-right: 5px;
          }
        }
        .content-txt {
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: nowrap;
          font-size: 12px;
          color: #959291;
        }
      }
      .chat-time {
        color: #959291;
        font-size: 12px;
        display: flex;
        flex-direction: column;
        justify-content: flex-end;
        align-items: flex-start;
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
      }
    }
  }
}
</style>
